package com.itheima.tanhua.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.tanhua.api.db.UserServiceApi;
import com.itheima.tanhua.exception.ConsumertException;
import com.itheima.tanhua.utils.AppJwtUtil;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhuan.pojo.db.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
* 业务逻辑处理类
* */
@Service
@Slf4j
public class UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    //远程调用
    @DubboReference
    private UserServiceApi userServiceApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    //环信
    /**
     * 发送短信验证
     * @param phone 手机号码
     */
    public boolean sendMsg(String phone) {
        //指定redis中存储手机验证码的key
        String redisKey="CODE_"+phone;
        //redis中验证码是否还生效
        String redisCode = redisTemplate.opsForValue().get(redisKey);
        boolean flag=true;
        if (StrUtil.isNotBlank(redisCode)){
            flag=false;
        }else {
            //生成6位数字验证码
            String code = "666666";
            //调用阿里sms服务向手机发送验证码（此处省略）
            //smsTemplate.sendSms(phone,code);
            //将验证码存储到redis中，有效期为5分钟
            redisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES);
        }
        return flag;
    }

    /**
     * 2、手机号与验证码登录
     * @param param  手机号：phone   验证码：verificationCode
     * @return
     */
    public Map loginVerification(Map<String, String> param) {
        //1、页面录入的手机号和验证码
        String phone = param.get("phone");
        String code = param.get("verificationCode");
        //2、通过手机号从redis中获取验证码
        String redisKey="CODE_"+phone;
        String redisCode = redisTemplate.opsForValue().get(redisKey);
        //如果redisCode为空，则直接返回
        if(StrUtil.isBlank(redisCode)){
            throw new ConsumertException("验证码不存在，请重新发送！");
        }
        //3、比较验证码code --->redisCode
        if(!StrUtil.equals(redisCode,code)){
            throw new ConsumertException("验证码不一致！");
        }
        //根据手机号查询数据库用户信息
        User user = userServiceApi.findByPhone(phone);

        boolean isNew=false;//默认是老用户
        //判断是新用户，需要注册
        if (ObjectUtil.isNull(user)){
            user=new User();
            user.setMobile(phone);
            user.setPassword(SecureUtil.md5("123456"));
            //注册用户数据
            Long id=userServiceApi.save(user);
            user.setId(id);
            isNew=true;


            //注册环信用户
            String hxUser = "hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if(create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userServiceApi.update(user);
            }
        }

        //4、生成token
        String token = AppJwtUtil.getToken(user.getId());//需要一个用户id?
        Map map=new HashMap();
        map.put("token",token);
        map.put("isNew",isNew);

        //删除redis验证码
        redisTemplate.delete(redisKey);
        return map;
    }

   //抽取token获取:当前登陆者id
    public Long getUserToken(String token){
        log.info("我在校验token");
        //1、token校验
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if(i==1 || i==2){
            throw new ConsumertException("token过期");
        }
        return Convert.toLong(claimsBody.get("id"));

    }

}
